/*
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public as published by
 * the Free Software Foundation, either version 3 of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.javaproxydiscoverer.workers;

import com.javaproxydiscoverer.ProxyConfiguration;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * A generic unix worker.
 * In practice all it does it look for the http_proxy environment variable.
 */
public class UnixWorker implements Worker {
    private static final Pattern PROXY_PATTERN = Pattern.compile("http://(\\w+:\\w+@)?(.[^:@]+)(:\\d+)?");

    /**
     * {@inheritDoc}
     */
    public ProxyConfiguration discoverProxy() {
        Matcher matcher = PROXY_PATTERN.matcher(System.getenv("http_proxy"));

        if (matcher.find()) {
            String host = "", username = null, password = null;
            int port = 80;

            int counter = 0;
            while (++counter <= matcher.groupCount()) {

                if (matcher.group(counter) == null)
                    continue;

                if (matcher.group(counter).contains("@")) {
                    // username & password
                    String authentication = matcher.group(counter);

                    username = authentication.substring(0, authentication.indexOf(":"));
                    password = authentication.substring(authentication.indexOf(":") + 1, authentication.length() - 1);
                } else if (matcher.group(counter).contains(":")) {
                    // port
                    port = Integer.valueOf(matcher.group(counter).substring(1));
                } else {
                    // host
                    host = matcher.group(counter);
                }
            }

            if (host.length() > 0)
                return new ProxyConfiguration("http://" + host, port, username, password);
            else
                return null;
        } else
            return null;
    }

    /**
     * {@inheritDoc}
     */
    public boolean applies() {
        return System.getenv("http_proxy") != null && PROXY_PATTERN.matcher(System.getenv("http_proxy")).matches();
    }
}
